using QFramework;
using Sirenix.OdinInspector;
using UnityEngine;

namespace DDA
{
    public class DDAResourceLoad : DDATreeNodeBase
    {
        public override int NextNodeMaxNum { get; } = 0;
        [ShowInInspector] public string ResourcePath;
        private DDAStart _ddaStart;

        public override string NodeName
        {
            get
            {
                if (this.Name.IsNullOrEmpty())
                {
                    return ResourcePath;
                }

                return this.Name;
            }
        }

        [ShowInInspector, ReadOnly, LabelText("作为封装的函数调用")]
        public bool IsFunction = false;
        public override bool Invoke()
        {
            base.Invoke();
            if (this._ddaStart != null)
            {
                // 如果是函数调用，每次都Invoke一次
                if (IsFunction)
                {
                    var result = this._ddaStart.Invoke();
                    if (result) this._ddaStart.Reset();
                    return result;
                }
                else
                {
                    // 不是则直接_ddaStart是否加载完成
                    return _ddaStart.isEnd;
                }
            }
            //加载资源并给DDAParser里面的赋值
            #if UNITY_EDITOR
            Debug.Log($"加载DDA资源:{ResourcePath}");
            #endif
            var resource = Resources.Load<DynamicDifficultAdjustTree>(ResourcePath);
            DDAParser.Instance.AddTree(resource);
            if (resource.RootNode is DDAStart start)
            {
                this._ddaStart = start;
                this.IsFunction = !this._ddaStart.isAutoInvoke;

                start.OnEnd = () =>
                {
                    DDAParser.Instance.RemoveTree(resource);
                };
                // 立即调用一次
                var result = this._ddaStart.Invoke();
                if (result && IsFunction) this._ddaStart.Reset();
                return result;
            }

            return true;
        }
        
    
        public override void Reset()
        {
            base.Reset();
            if (this._ddaStart != null)
            {
                this._ddaStart.Reset();
            }

            this._ddaStart = null;
        }
    }
}
